package com.cpd.blog.common.utils;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @Author: copydown
 * @Date: 2022/04/28/16:41
 */
@Component
@RequiredArgsConstructor
public class RedisUtil {

    private final RedisTemplate<String, Object> redisTemplate;

    public void checkAndDelete(String key) {
        Optional<Boolean> redisKey = Optional.ofNullable(redisTemplate.hasKey(key));
        if (redisKey.isPresent() && redisKey.get()) {
            redisTemplate.delete(key);
        }
    }

    public <T> T checkAndGetObj(String key, Class<T> clazz) {
        Optional<String> redisKey = Optional.ofNullable(get(key));
        return redisKey.map(s -> JSON.parseObject(s, clazz)).orElse(null);
    }

    @SuppressWarnings("all")
    public <T> T get(String key) {
        return (T) redisTemplate.opsForValue().get(key);
    }

    public void set(String key, Object obj, long timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, obj, timeout, timeUnit);
    }

    public Boolean setIfPresent(String key, Object obj) {
        return redisTemplate.opsForValue().setIfPresent(key, obj);
    }

    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    public <T> void setHash(String key1, T key2, T value) {
        redisTemplate.opsForHash().put(key1, String.valueOf(key2), String.valueOf(value));
    }

    public <T> String deleteHashWithCount(String key1, T key2) {
        String value = (String) redisTemplate.opsForHash().get(key1, String.valueOf(key2));
        redisTemplate.opsForHash().delete(key1, String.valueOf(key2));
        return value;
    }

    public <T> String compareHashAndGet(String key1, T key2) {
        return String.valueOf(redisTemplate.opsForHash().get(key1, String.valueOf(key2)));
    }

}
